<?php
/**
 * 订单管理
 * Created by Sublime Text 3.
 * @authors Rejeo (rejeo@qq.com)
 * @date    2018-05-13 22:07:59
 * @version $Id$
 */
namespace app\index\controller;

use app\index\controller\Base;
use think\Request;

class Order extends Base
{
    public function index(Request $request)
    {
        $data = [];
        $user = $this->getLoginUser();
        if (!$user) {
            $this->error('请登录！', 'user/login');
        }
        $id = $request->get('id', 0, 'intval');
        $count = $request->get('count', 0, 'intval');
        $total_price = $request->get('total_price');
        // 在业务中一定要严格校验 tp5中通过 validate校验器 方法校验
        if (!$id || !$count || !$total_price) {
            $this->error('参数不合法！');
        }
        if (empty($_SERVER['HTTP_REFERER'])) {
            $this->error('请求不合法！');
        }
        $deal = model('Deal')->find($id);
        $deal = $deal->toArray();
        if (!$deal || $deal['status'] !== 1) {
            $this->error('商品不存在！');
        }
        if ($total_price !=($deal['current_price']*$count)) {
            $this->error('购买失败！');
        }
        $orderSn = setOrderSn();
        $data = [
            'out_trade_no' => $orderSn,
            'user_id'      => $user['id'],
            'username'     => $user['username'],
            'deal_id'      => $id,
            'deal_count'   => $count,
            'total_price'  => $total_price,
            'referer'      => $_SERVER['HTTP_REFERER'],
        ];

        $orderId = model('order')->add($data);

        if (!$orderId) {
            $this->error('订单处理失败！');
        }

        $this->redirect(url('pay/index',['id'=>$orderId]));

    }

    public function confirm(Request $request)
    {
        if (!$this->getLoginUser()) {
            $this->error('请登录！', 'user/login');
        }
        $id = $request->get('id', 0, 'intval');
        $count = $request->get('count', 0, 'intval');
        if (!$id || !$count) {
            $this->error('参数不合法！');
        }
        $deal = model('Deal')->find($id);
        $deal = $deal->toArray();
        if (!$deal || $deal['status'] !== 1) {
            $this->error('商品不存在！');
        }
        $this->assign([
            'deal'=>$deal,
            'count'=>$count,
        ]);
        return $this->fetch();
    }
}
